/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *deleteNode(TreeNode *root, int key)
    {
        if (root == nullptr)
        {
            return nullptr;
        }
        if (key == root->val)
        {
            if (root->left == nullptr)
            {
                return root->right;
            }
            if (root->right == nullptr)
            {
                return root->left;
            }
            if (root->left->right == nullptr)
            {
                root->left->right = root->right;
                return root->left;
            }
            TreeNode *leftMax = root->left->right;
            TreeNode *leftMaxAhead = root->left;
            while (leftMax->right != nullptr)
            {
                leftMax = leftMax->right;
                leftMaxAhead = leftMaxAhead->right;
            }
            root->val = leftMax->val;
            leftMaxAhead->right = leftMax->left;
            return root;
        }
        if (key < root->val)
        {
            root->left = deleteNode(root->left, key);
        }
        else
        {
            root->right = deleteNode(root->right, key);
        }
        return root;
    }
};